import re

from django.contrib.auth.backends import ModelBackend

from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据,定义完之后需要在dev那边使用这个配置
    """
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }


class UsernameMobileAuthBackend(ModelBackend):
    """定义authenticate方法使用的后端，如果不设置就默认的ModelBackend"""
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 判断是手机还是用户名
        try:
            # 查询用户
            if re.match(r'^1[3-9]\d{9}$', username):
                user = User.objects.get(mobile=username)
            else:
                user = User.objects.get(username=username)
        except:
            return None
        # 判断密码
        if not user.check_password(password):
            return None
        # 返回用户
        return user

